from PIL import Image
import numpy as np
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms

"""
transforms 转换工具，数据预处理使用
"""
img = Image.open("../dataset/train/ants/0013035.jpg")
writer = SummaryWriter("logs03")

#numpy 将图片转换成数组
img_array = np.array(img)
print(img_array.shape)

# toTensor 将图片转换成Tensor
print(type(img))
transforms_toTensor = transforms.ToTensor()
img_tensor = transforms_toTensor(img)
print(type(img_tensor))
print(img_tensor)
writer.add_image("ToTensor" , img_tensor)

# Normalize  给定均值：(R,G,B) 方差：（R，G，B），将会把Tensor正则化。即：Normalized_image=(image-mean)/std。
transforms_Normalize = transforms.Normalize([0.5,0.5,0.5] , [0.5,0.5,0.5])
img_tensorToNorm = transforms_Normalize(img_tensor)
print(img_tensorToNorm)
writer.add_image("Normalize" , img_tensorToNorm)

# Resize  重置图片大小
transforms_Resize = transforms.Resize((512,512))
img_resize = transforms_Resize(img)
print(type(img_resize))
print(img_resize.size)
# PIL.Image 格式的 ，需要指定dataformats
writer.add_image("Resize" , np.array(img_resize) , dataformats="HWC")

# Compose  组合使用
transforms01_toTensor = transforms.ToTensor()
transforms02_Resize = transforms.Resize(512)
transforms_Compose = transforms.Compose([transforms01_toTensor , transforms02_Resize])
img_Compose = transforms_Compose(img)
print(type(img_Compose))
print(img.size)
writer.add_image("Compose" , img_Compose)

# RandomCrop 随机裁剪
transforms01_RandomCrop = transforms.RandomCrop(256)
transforms02_ToTensor = transforms.ToTensor()
transform_RandomCropAndToTensor = transforms.Compose([transforms01_RandomCrop , transforms02_ToTensor])
step = 0
for i in range(10):
    writer.add_image("RandomCrop" , transform_RandomCropAndToTensor(img) , global_step=step)
    step+=1

writer.close()




